<!--  -->
<template>
  <div>
    <div
      style="
        display: flex;
        align-items: baseline;
        line-height: 50px;
        padding-bottom: 10px;
      "
    >
      <el-select
        v-model="value"
        placeholder="请选择"
        clearable
        style="width: 120px"
      >
        <el-option
          v-for="item in cities"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{
            item.value
          }}</span>
        </el-option>
      </el-select>
      <el-input
        placeholder="请输入内容"
        v-model="keyword"
        clearable
        class="TopSearch"
      >
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="searchButton"
        >搜索</el-button
      >
      <el-button type="primary" icon="el-icon-plus" @click="add"
        >新增</el-button
      >
      <add-form ref="addForm" @formSubmit="handleformSubmit"></add-form>
    </div>
    <!-- 表格部分 -->
    <el-table
      :data="filtertabList"
      style="line-height: 50px; border-radius: 5px"
      border
    >
      <el-table-column prop="name" label="用户名" width="180">
      </el-table-column>
      <el-table-column prop="amount" label="账户余额" width="180">
      </el-table-column>
      <el-table-column prop="region" label="地址" width="180">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.state === '生效中' ? 'success' : 'warning'"
            >{{ scope.row.state }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="time" label="注册时间" width="180">
      </el-table-column>
      <el-table-column label="头像" width="180">
        <template slot-scope="scope">
          <el-image
            style="width: 40px; height: 40px"
            :src="scope.row.ImageUrl"
            :preview-src-list="[scope.row.ImageUrl]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 30, 40]"
      :page-size="pageSize"
      :layout="layout"
      :total="total"
      style="display: flex; margin-top: 1rem"
    >
    </el-pagination>
    <!-- 操作功能部分 -->
    <div>
      <el-dialog :visible.sync="dialogFormVisible" center>
        <p
          style="
            line-height: 50px;
            font-size: 20px;
            margin: 10px 0;
            text-align: center;
          "
        >
          编辑表格
        </p>
        <el-form
          :model="form"
          class="TableEdit"
          style="display: flex; justify-content: space-evenly; flex-wrap: wrap"
        >
          <el-form-item label="用户名" class="dialog-form">
            <el-input
              v-model="form.name"
              autocomplete="on"
              class="dialog-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="账户余额" class="dialog-form">
            <el-input
              v-model="form.amount"
              autocomplete="off"
              class="dialog-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="现地址" class="dialog-form">
            <el-input
              v-model="form.region"
              autocomplete="off"
              class="dialog-input"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否启用" class="dialog-form">
            <el-select
              v-model="form.state"
              placeholder="生效状态"
              class="dialog-input"
            >
              <el-option label="启用" value="true"></el-option>
              <el-option label="未启用" value="false"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="换头像" class="dialog-form">
            <el-input
              v-model="form.ImageUrl"
              autocomplete="off"
              class="dialog-input"
              placeholder="请输入url"
            ></el-input>
          </el-form-item>
          <el-form-item label="注册时间" class="dialog-form">
            <el-input
              v-model="form.time"
              autocomplete="off"
              class="dialog-input"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="determine">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { cloneDeep } from "lodash"; // 安装lodash库
import addForm from "@/views/components/mian/add-form";
import axios from "axios";

export default {
  name: "UsrfulForms",
  components: {
    addForm,
  },
  data() {
    return {
      currentPage: 1, //当前页数
      pageSize: 5, //每页显示个数
      total: 0, //页码总数
      layout: "total, sizes, prev, pager, next, jumper", //组件布局
      keyword: "", // 用户输入的关键词
      filtertabList: [], // 过滤后的列表项
      selectedRowIndex: "",
      FormData: [], //存储完整数据的列表项
      cities: [
        {
          value: "Beijing",
          label: "北京",
        },
        {
          value: "Shanghai",
          label: "上海",
        },
      ],
      value: "",
      // url: "https://ts2.tc.mm.bing.net/th?id=OIP-C.JCEcaQJVR_vC2kgt6BGZlAAAAA&w=247&h=252&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2",
      dialogFormVisible: false,
      form: {
        name: "",
        region: "",
        amount: "",
        state: "",
        ImageUrl: "",
        time: "",
      },
    };
  },
  watch: {
    // 监听关键词的变化
    keyword: {
      // immediate: true,  // 立即执行一次handler
      handler(value) {
        // 监听函数
        // 根据关键词实时过滤列表项
        if (value) {
          this.filtertabList = this.FormData.filter((t) => {
            return t.name.indexOf(value) !== -1;
          });
          this.layout = "total";
          this.total = this.filtertabList.length;
        } else {
          this.layout = "total, sizes, prev, pager, next, jumper";
          this.updateDisplay();
        }
      },
    },
  },
  mounted() {
    this.GetForm();
  },
  methods: {
    // 搜索按钮功能
    searchButton() {
      if (this.keyword) {
        // 如果关键词不为空，根据关键词再次过滤列表并更新filtertabList
        this.filtertabList = this.FormData.filter((self) => {
          return self.name.indexOf(this.keyword) !== -1;
        });
        this.layout = "total";
        this.total = this.filtertabList.length;
      } else {
        this.layout = "total, sizes, prev, pager, next, jumper";
        this.updateDisplay();
      }
    },
    GetForm() {
      axios
        .get("/add/form")
        .then(({ data: res }) => {
          // 处理成功情况
          // console.log(res.formData);
          if (res.code == 200) {
            this.FormData = res.formData;
            this.GetImage(); //获取随机头像
          }
        })
        .catch((error) => {
          // 处理错误情况
          console.log(error);
          this.$message.error("错了哦，这是一条错误消息");
        });
    },
    // 获取头像
    GetImage() {
      axios
        .get("https://v2.xxapi.cn/api/head")
        .then((response) => {
          const res = response.data;
          if (res.code === 200) {
            const imageUrls = res.data; // 获取到的图片链接
            // 遍历 FormData 数组，为每个对象的 ImageUrl 字段赋值
            this.FormData = this.FormData.map((item) => {
              return { ...item, ImageUrl: imageUrls };
            });
            this.updateDisplay(); //初始化filtertablist数组的数据
            console.log(this.filtertabList); // 查看更新后的 filtertabList
          }
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("错了哦，这是一条错误消息");
        });
    },
    // 操作按钮
    handleEdit(index, row) {
      // row.id 去发送一次后端请求，获取单行的数据用于编辑
      // this.form = row
      // Object.assign(this.form, row)     //ES6拷贝语法
      this.form = cloneDeep(row);
      this.selectedRowIndex = index;
      console.log(index, row);
      this.dialogFormVisible = true;
    },
    // 操作功能确定按钮
    determine() {
      this.FormData.splice(this.selectedRowIndex, 1, this.form);
      this.selectedRowIndex = "";
      this.dialogFormVisible = false;
      console.log(this.selectedRowIndex, this.form);
    },
    add() {
      this.$refs.addForm.show();
    },
    // 新增数据监听方法:监听子组件传过来的数据并渲染
    handleformSubmit(formData) {
      this.FormData.push(formData);
      this.updateDisplay(); //更新显示数据
      this.$message.success("添加成功！");
      // console.log(formData.name);
    },
    // 删除表格方法：1、通过index获得此行下标，row获得此行的数据；2、插入messageBox弹框；3、数组方法splice操作数组执行删除事件
    handleDelete(index, row) {
      console.log(index, row);
      // this.tableData.splice(index, 1)
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.FormData.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分页部分操作-处理每页显示条数变化
    handleSizeChange(val) {
      this.pageSize = val; //将传入的显示条数赋值更新
      this.updateDisplay(); //重新计算显示数据
    },
    //分页部分操作-处理页码变化
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.updateDisplay();
    },
    // 更新显示数据
    updateDisplay() {
      const startIndex = this.pageSize * (this.currentPage - 1); //计算起始索引
      const endIndex = startIndex + this.pageSize; //计算结束索引
      this.filtertabList = this.FormData.slice(startIndex, endIndex); //更新显示数据
      this.total = this.FormData.length; //更新数据总数量
    },
  },
};
</script>
<style scoped='less'>
/* 搜索框 */
.TopSearch {
  width: 300px;
  margin: 0 10px;
}
.TableEdit {
  display: flex;
}
/* 编辑页表格样式 */
.dialog-form {
  display: flex;
}
/* 编辑按钮中的输入框样式 */
.dialog-input {
  width: 200px;
  margin: 0 10px;
}
</style>